package cn.itcast.service;

import cn.itcast.mapper.PermissionMapper;
import cn.itcast.mapper.RoleMapper;
import cn.itcast.mapper.UserMapper;
import cn.itcast.pojo.Permission;
import cn.itcast.pojo.Role;
import cn.itcast.pojo.User;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.util.Set;


@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public User findByUsername(String username) {
        User user = userMapper.findByUsername(username);
        if (user == null) {
            return null;
        }
        //获取当前用户的id
        Integer userId = user.getId();
        Set<Role> roles = roleMapper.findByUserId(userId);
        if (roles != null && roles.size() > 0) {
            for (Role role : roles) {
                Integer roleId = role.getId();
                Set<Permission> permissions = permissionMapper.findByRoleId(roleId);
                if (permissions != null && permissions.size() > 0){
                    role.setPermissions(permissions);
                }
            }
        }
        user.setRoles(roles);
        return user;
    }
}
